package com.yxjx.duoxue.course;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Properties;
import java.util.concurrent.Executors;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.PopupWindow;
import android.widget.RatingBar;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;


import com.tencent.stat.StatService;
import com.thirdparty.neutra.autoscrollloopviewpager.AutoScrollLoopViewPager;
import com.thirdparty.trinea.autoscrollviewpager.AutoScrollViewPager;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.bean.SocializeEntity;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.listener.SocializeListeners.SnsPostListener;
import com.umeng.socialize.media.QQShareContent;
import com.umeng.socialize.media.QZoneShareContent;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.sso.QZoneSsoHandler;
import com.umeng.socialize.sso.UMQQSsoHandler;
import com.umeng.socialize.weixin.controller.UMWXHandler;
import com.yxjx.duoxue.BaseActionBarActivity;
import com.yxjx.duoxue.Constants;
import com.yxjx.duoxue.HomePageActivity;
import com.yxjx.duoxue.R;
import com.yxjx.duoxue.ShareTextHelper;
import com.yxjx.duoxue.Yx;
import com.yxjx.duoxue.YxSegment;
import com.yxjx.duoxue.activities.ActivityIntroductionActivity;
import com.yxjx.duoxue.activities.RichTextHelper;
import com.yxjx.duoxue.ad.AdPageActivity;
import com.yxjx.duoxue.audition.ApointmentAuditionActivity;
import com.yxjx.duoxue.comment.AllThumbnailsView;
import com.yxjx.duoxue.comment.CommentFunctionView;
import com.yxjx.duoxue.comment.DetailedCommentActivity;
import com.yxjx.duoxue.comment.ViewPagerActivity;
import com.yxjx.duoxue.course.HomePageFragment.AdViewPagerAdapter;
import com.yxjx.duoxue.customview.OutScrollView;
import com.yxjx.duoxue.customview.YxDetailedInfoView1;
import com.yxjx.duoxue.customview.YxDetailedInfoView1.YxListAdapter1;
import com.yxjx.duoxue.customview.YxTabHost;
import com.yxjx.duoxue.customview.YxTabHost.Callback;
import com.yxjx.duoxue.datamodel.DMAdItem;
import com.yxjx.duoxue.datamodel.DMAllComments;
import com.yxjx.duoxue.datamodel.DMComment;
import com.yxjx.duoxue.datamodel.DMCommentLevelAvg;
import com.yxjx.duoxue.datamodel.DMProduct;
import com.yxjx.duoxue.datamodel.DMTeacher;
import com.yxjx.duoxue.datamodel.ResponseObject;
import com.yxjx.duoxue.datamodel.course.CourseDetailDTS;
import com.yxjx.duoxue.datamodel.course.DMCourse;
import com.yxjx.duoxue.global.Globals;
import com.yxjx.duoxue.lbs.LocationIndicatorActivity;
import com.yxjx.duoxue.mta.stat.StatHelper;
import com.yxjx.duoxue.my.UserLoginActivity;
import com.yxjx.duoxue.my.UserRegActivity;
import com.yxjx.duoxue.network.MsgCode;
import com.yxjx.duoxue.network.NwUtils;
import com.yxjx.duoxue.network.UserLoginResponse;
import com.yxjx.duoxue.network.UserReg;
import com.yxjx.duoxue.payment.CourseProductsView;
import com.yxjx.duoxue.payment.ProductSelectionActivity;
import com.yxjx.duoxue.utils.ShareUtils;
import com.yxjx.duoxue.utils.UIHelper;
import com.yxjx.duoxue.utils.Utils;

public class CourseIntroductionActivity extends BaseActionBarActivity {
	
	private ArrayList<DMTeacher> mDMTeachers = null;
	private DMCourse mCurrentCourse = null;
	
	public static final int REQ_CODE_FREE_REG = 1;
	public static final int REQ_CODE_LOGIN_FOR_FAVOURITE = 2;
	public static final int REQ_CODE_LOGIN_FOR_REG = 3;
	public static final int REQ_CODE_LOGIN_FOR_ADD_COMMENT = 4;
	
	private ArrayList<DMComment> mALlCommentsArray;
	private DMAllComments mAllCommentsObject;
	private CommentFunctionView commentView;

	// 是否支持免费预约试听
	private int supportBook;
	private int supportBuy;
	private AutoScrollLoopViewPager imageViewPager;
	private ImageViewPagerAdapter imageViewPagerAdapter;
	private Context mContext;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fragment_course_intro);
		
		customizeActionBarTitle("课程简介");
		mContext = this;
		mActionBar.getCustomView().findViewById(R.id.share).setVisibility(View.VISIBLE);
		mActionBar.getCustomView().findViewById(R.id.favourite).setVisibility(View.VISIBLE);
		mActionBar.getCustomView().findViewById(R.id.share).setOnClickListener(mClickListener);
		mActionBar.getCustomView().findViewById(R.id.favourite).setOnClickListener(mClickListener);
		
		mScrollView = (ScrollView) findViewById(R.id.scrollView);
		UIHelper.setClickListener((View) mScrollView.getParent(), R.id.school_button, mClickListener);
		UIHelper.setClickListener((View) mScrollView.getParent(), R.id.contact_now, mClickListener);
		UIHelper.setClickListener((View) mScrollView.getParent(), R.id.location_root, mClickListener);
		UIHelper.setClickListener((View) mScrollView.getParent(), R.id.dailer, mClickListener);
		
		/// 轮播图
		imageViewPager = (AutoScrollLoopViewPager) mScrollView.findViewById(R.id.course_image_turn).findViewById(R.id.pager);

		mProductView = (CourseProductsView) mScrollView.findViewById(R.id.course_products);
		// TODO: customize page tabs start
		OutScrollView mOutScroll = (OutScrollView) findViewById(R.id.scrollView);
		pagers = (ViewPager) findViewById(R.id.pagers);
		pagers.setAdapter(new ViewPagerAdapter(getSupportFragmentManager()));
		pagers.setOffscreenPageLimit(2);
		tabs = findViewById(R.id.head_tabs);
		UIHelper.setText(tabs, R.id.text, "课程详情");
		// customize page tabs end
		tryLoadDataFromWeb();

	}
	
	/// 轮播图
	class ImageViewPagerAdapter extends PagerAdapter {
		
		private ArrayList<String> mDataList = new ArrayList<String>();
		private String allDataUrls = "";
		
		
		public ArrayList<String> getDataList() {
			return mDataList;
		}
		
		public ImageViewPagerAdapter(String urls) {
			allDataUrls  = urls;
			mDataList = AllThumbnailsView.initUrls(urls);
			
		}
		
		@Override
		public int getCount() {
			return mDataList == null ? 0 : mDataList.size();
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}
		
		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			container.removeView((View) object);
		}
		
		@Override
		public Object instantiateItem(ViewGroup container, final int position) {
			
			View item = LayoutInflater.from(CourseIntroductionActivity.this).inflate(R.layout.segment_home_page_ad, null);
			String url = mDataList.get(position);
			
			UIHelper.asyncLoadImage((ImageView) item.findViewById(R.id.ad_image), url, R.drawable.class_detail);
			container.addView(item);
			// click Listener
			item.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					StatHelper.addKVEvent(mContext, "event_course_viewpager_click");
					Intent intent = new Intent(CourseIntroductionActivity.this, ViewPagerActivity.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					intent.putExtra(AllThumbnailsView.KEY_EXTRA_IMAGES, allDataUrls);
					intent.putExtra(AllThumbnailsView.KEY_EXTRA_INDEX, position);
					CourseIntroductionActivity.this.startActivity(intent);
				}
			});
			
			return item;
		}
	}
	
	private void initImageTurnDone() {
		if (mCurrentCourse == null || UIHelper.isEmpty(mCurrentCourse.getImageTurn())) {
			return;
		}
		
		final String urls = mCurrentCourse.getImageTurn();
		// set initialization in middle.
		if (UIHelper.isEmpty(urls)) {
			return;
		}

		ArrayList<String> urlArray = AllThumbnailsView.initUrls(urls);
		final int stepLen = urlArray == null ? 0 : urlArray.size();
		imageViewPagerAdapter = new ImageViewPagerAdapter(urls);
		imageViewPager.setAdapter(imageViewPagerAdapter);
		
		imageViewPager.setCurrentItem(0);
		imageViewPager.setOnPageChangeListener(new OnPageChangeListener() {
			
			@Override
			public void onPageSelected(int arg0) {
			}
			
			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				if (arg1 == 0.0) {
					int indicatorIndex = arg0 % stepLen;
					setAdIndicator(stepLen, indicatorIndex);
				}
			}
			
			@Override
			public void onPageScrollStateChanged(int arg0) {
			}
		});
		
		// indicator
		if (stepLen > 0) {
			initAdIndicator(stepLen);
		}
		imageViewPager.startAutoScroll(5000);
		imageViewPager.setInterval(5000);
		imageViewPager.setStopScrollWhenTouch(true);
	}
	
	private void setAdIndicator(int stepLen, int indicatorIndex) {
		TextView text = (TextView) mScrollView.findViewById(R.id.course_image_turn).findViewById(R.id.indicator);
		
		/// 如果url 为 空图片 "＊image_turn_default_*", ind改为0/0
		if (imageViewPagerAdapter.getDataList() != null
				&& imageViewPagerAdapter.getDataList().size() == 1
				&& imageViewPagerAdapter.getDataList().get(0)
				.contains("image_turn_default")) {
			text.setText("0/0");
			return;
		}
			
		text.setText("" + (indicatorIndex + 1) + "/" + stepLen);
	}
	
	private void initAdIndicator(int stepLen) {
		setAdIndicator(stepLen, 1);
	}
	/// 轮播图

	public ArrayList<DMTeacher> getTeachers() {
		return mDMTeachers;
	}
	
	private Observee teachersDataChangeNotifier = null;
	private ViewPager pagers;
	
	@Override
	protected void onResume() {
		super.onResume();
		
		// 在onResume时，重新设置内嵌控件的高度。
		// pagers的高度应该为outer的高度减去tabs的高度
		pagers.post(new Runnable() {
			@Override
			public void run() {
				int outHeight = mScrollView.getHeight();
				int tabHeight = tabs.getHeight();
				int innerWidth = pagers.getWidth();
				pagers.getLayoutParams().width = innerWidth;
				pagers.getLayoutParams().height = outHeight - tabHeight;
				Utils.logd("outHeight = " + outHeight + ",tabHeight = "
						+ tabHeight);
				Utils.logd("width = " + pagers.getLayoutParams().width
						+ ",height = " + pagers.getLayoutParams().height);
				pagers.invalidate();
			}
		});
		UIHelper.resetScroll(CourseIntroductionActivity.this, R.id.scrollView);

	}

	private void tryLoadDataFromWeb() {
		// 尝试去加载数据。
		mCourseId = getIntent().getExtras().getString(NwUtils.KEY_ID);
		
		if (Utils.hasKeyValue(getIntent(), Yx.KEY_OPEN_BY, Yx.VALUE_OPEN_BY_AD_CLICK)) {
			StatHelper.addKVEvent(mContext, "event_home_ad_show", 
					StatHelper.KEY_AD, StatHelper.KEY_COURSE + mCourseId);
		} else if (Utils.hasKeyValue(getIntent(), Yx.KEY_OPEN_BY, Yx.VALUE_OPEN_BY_REF_COURSE)) {
			StatHelper.addKVEvent(mContext, "event_home_ref_course_show", 
					StatHelper.KEY_COURSE, mCourseId);
		}
		
		
		if (!UIHelper.isEmpty(mCourseId)) {
			
			LoadingCourseAsyncTask lat = new LoadingCourseAsyncTask();
			JSONObject params = new JSONObject();
			try {
				params.put(NwUtils.KEY_AREA, "0_0");
				params.put(NwUtils.KEY_ID, mCourseId);
			} catch (JSONException e) {
				e.printStackTrace();
			}
			lat.execute(NwUtils.REQ_COURSE_INFO, params.toString());
		}
	}
	
	public class ViewPagerAdapter extends FragmentStatePagerAdapter  {

		public ViewPagerAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int position) {
			Fragment ret = null;
			Bundle bundle = new Bundle();
			int layoutId;
			if (position == 0) {
				layoutId = R.layout.segment_h5;
				bundle.putInt(YxSegment.KEY_SEGMENT_TYPE, Yx.TYPE_H5);
				bundle.putString(YxSegment.KEY_URL, NwUtils.URL_COURSE_DESC + mCourseId + NwUtils.webTail());
			} else{
				layoutId = R.layout.segment_teacher_list;
				bundle.putInt(YxSegment.KEY_SEGMENT_TYPE, Yx.TYPE_SCROLLER);
			}
			YxSegment fragment = YxSegment.getSegment(layoutId, bundle);
			return fragment;
		}

		@Override
		public int getCount() {
			return 1;
		}
	}
	
	private DMAllComments getComments() {
		JSONObject params = new JSONObject();
		try {
			params.put("type", "" + DetailedCommentActivity.convertType(Yx.TYPE_ITEM_COURSE));
			params.put("id", mCourseId);
			// mAdapter 长度比 mAllComments 大一
			params.put("startIndex", 0);
			params.put("count", 1);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return DetailedCommentActivity.loadAllCommentsListByParams(params, this);
	}
	
	class LoadingCourseAsyncTask extends
			AsyncTask<String, Integer, DMCourse> {

		@Override
		protected DMCourse doInBackground(String... arg0) {

			try {
				DMCourse course = null;
				String url = arg0[0];
				JSONObject jo = null;
				if (!UIHelper.isEmpty(arg0[1])) {
					jo = new JSONObject(arg0[1]);
				}
				UserLoginResponse ulRsp = UserLoginResponse.getInstance(getApplicationContext());
				course = (DMCourse) NwUtils.requestDataInfo(url, jo, ulRsp, CourseIntroductionActivity.this);
				mAllCommentsObject = getComments();
				mALlCommentsArray = mAllCommentsObject.getAllComments();

				return course;
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (JSONException e) {
				e.printStackTrace();
			}
			
			return null;
		}

		@Override
		protected void onPostExecute(DMCourse result) {
			super.onPostExecute(result);
			
			mCurrentCourse = result;
			if (mCurrentCourse == null) {
				UIHelper.showTips(mScrollView, R.string.check_nw_and_try);
				finish();
				return;
			}
			
			// share function:
			customizeShare(NwUtils.SHARE_COURSE + "id=" + mCourseId,
					mCurrentCourse);
			
			// update course text info.
			UIHelper.setText(mScrollView, R.id.course_name, result.getCourseName());
			UIHelper.setText(mScrollView, R.id.category, "类型：" + result.getCourseType2());
			UIHelper.setText(mScrollView, R.id.requirement, result.getAgeDesc());
//			UIHelper.setText(mScrollView, R.id.school_name,
//					result.getSchoolFullName());
			UIHelper.setText(mScrollView, R.id.location, result.getAddress());
			supportBook = result.getSupportBook();
			supportBuy = getSupportBuyCount();
			if (supportBook != 1) {
				findViewById(R.id.contact_now).setBackgroundResource(
						R.drawable.shape_image_round_background_disabled);
				findViewById(R.id.contact_now).setVisibility(View.GONE);
				findViewById(R.id.dailer_left_divider).setVisibility(View.GONE);
			}
			if (supportBuy == 0) {
				findViewById(R.id.buy_now).setVisibility(View.GONE);
			}
			
			commentView = (CommentFunctionView) findViewById(R.id.comment_function);
			TextView addText = (TextView) commentView.findViewById(R.id.add_comment);
			if (mALlCommentsArray != null && mAllCommentsObject.getTotalNum() > 0) {
				commentView.init(mALlCommentsArray.get(0));
				commentView.setNum(mAllCommentsObject.getTotalNum());
			} else {
				commentView.setNum(mAllCommentsObject.getTotalNum());
				commentView.initAsNoComment();
			}
			
			// 商品列表
			mProductView.setData(result.getProducts(), true);
			if (result.getProducts() != null) {
				for (DMProduct  item : result.getProducts()) {
					Utils.logd("CMM7 getProduct = " + item);
				}
			}
			
			// 更新favStatus
			mActionBar.getCustomView().findViewById(R.id.favourite).setSelected(result.getFavStatus() == 1);
			// customize course info and achievement.
			RichTextHelper rh = new RichTextHelper();
			rh.parseHtmlString(result.getCourseAchievement());
			ArrayList<Object> datas = rh.getData();
			ArrayList<Integer> types = rh.getItemTypes();
//			mAchievementAdapter.setData(types, datas);
			
			rh = new RichTextHelper();
			rh.parseHtmlString(result.getCourseDescription());
			datas = rh.getData();
			types = rh.getItemTypes();
//			mCourseInfoAdapter.setData(types, datas);
			
			// customize teachers
			mDMTeachers = result.getTeachers();
			if (teachersDataChangeNotifier != null) {
				teachersDataChangeNotifier.notifyDataChanged();
			}
//			mTearchersAdapter.setData(types, datas);
			Utils.addCourseOnlyLabels((ViewGroup) mScrollView.findViewById(R.id.labels), result.getAuthArray());
			Utils.addSchoolOnlyLabels((TextView) mScrollView
					.findViewById(R.id.school_name), result.getSchoolFullName(), result.getSchool().getAuthArray());
			
			/// 课程7维度属性
			fillSchollDetailAttrib(result);
			initImageTurnDone();
			/// 课程7维度属性
			
			/// MTA stat start
			Properties prop = StatHelper.getBasicProp(CourseIntroductionActivity.this);
			prop.put(StatHelper.KEY_COURSE, mCurrentCourse.getCourseId());
			StatService.trackCustomKVEvent(CourseIntroductionActivity.this, "event_course_item_show", prop);
			/// MTA stat end
			
			UIHelper.resetScroll(CourseIntroductionActivity.this, R.id.scrollView);
			// dismiss loading dialog.
			dismissDialog();
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case REQ_CODE_FREE_REG:
			if (resultCode == RESULT_OK) {
				Toast.makeText(getApplicationContext(), "课程预约试听成功", Toast.LENGTH_SHORT).show();
			}
			break;
		case REQ_CODE_LOGIN_FOR_FAVOURITE:
			if (resultCode == RESULT_OK) {
				favaouriteCourse();
			}
			break;
		case REQ_CODE_LOGIN_FOR_REG:
			if (resultCode == RESULT_OK) {
				bookCourse();
			}
			break;
		case REQ_CODE_LOGIN_FOR_ADD_COMMENT:
			if (resultCode == RESULT_OK) {
				commentView.addingComment();
			}
			break;
		default:
			break;
		}
	}
	
	private void fillSchollDetailAttrib(DMCourse result) {
		if (result == null || result.getCourseDetail() == null) {
			findViewById(R.id.course_detail_7).setVisibility(View.GONE);
		} else {
			UIHelper.setText(findViewById(R.id.course_detail_7).findViewById(R.id.item_1), R.id.key, "品牌历史：");
			UIHelper.setText(findViewById(R.id.course_detail_7).findViewById(R.id.item_2), R.id.key, "累计学员：");
			UIHelper.setText(findViewById(R.id.course_detail_7).findViewById(R.id.item_3), R.id.key, "教学设施：");
			UIHelper.setText(findViewById(R.id.course_detail_7).findViewById(R.id.item_4), R.id.key, "卫生状况：");
			UIHelper.setText(findViewById(R.id.course_detail_7).findViewById(R.id.item_5), R.id.key, "老师数量：");
			UIHelper.setText(findViewById(R.id.course_detail_7).findViewById(R.id.item_6), R.id.key, "平均教龄：");
			UIHelper.setText(findViewById(R.id.course_detail_7).findViewById(R.id.item_7), R.id.key, "老师资历：");

			CourseDetailDTS item = result.getCourseDetail();
			UIHelper.setText(findViewById(R.id.course_detail_7).findViewById(R.id.item_1), R.id.value, item.getBrandHistory());
			UIHelper.setText(findViewById(R.id.course_detail_7).findViewById(R.id.item_2), R.id.value, item.getBrandStudentCount());
			UIHelper.setText(findViewById(R.id.course_detail_7).findViewById(R.id.item_3), R.id.value, item.getEnvFacilities());
			UIHelper.setText(findViewById(R.id.course_detail_7).findViewById(R.id.item_4), R.id.value, item.getEnvHealth());
			UIHelper.setText(findViewById(R.id.course_detail_7).findViewById(R.id.item_5), R.id.value, item.getTeacherCount());
			UIHelper.setText(findViewById(R.id.course_detail_7).findViewById(R.id.item_6), R.id.value, item.getTeacherAge());
			UIHelper.setText(findViewById(R.id.course_detail_7).findViewById(R.id.item_7), R.id.value, item.getTeacherQualifier());
		}
		
	}

	private void dismissDialog() {
		mScrollView.post(new Runnable() {
			
			@Override
			public void run() {
				findViewById(R.id.root).setVisibility(View.VISIBLE);
				findViewById(R.id.loading).setVisibility(View.INVISIBLE);
			}
		});
	}
	
	private void fillCourseInfoAdapterData(YxListAdapter1 mCourseInfoAdapter) {
		ArrayList<Integer> itemTypes = new ArrayList<Integer>();
		ArrayList<Object> data = new ArrayList<Object>();
		for (int i = 0; i < 3; i++) {
			itemTypes.add(0);
			itemTypes.add(1);
			data.add(new Object());
			data.add(Integer.valueOf(1));
		}
		mCourseInfoAdapter.setData(itemTypes, data);
	}
	
	private void fillTeachersAdapterData(YxListAdapter1 YxListAdapter1) {
		fillTeachersAdapterData(YxListAdapter1, null);
	}
	
	private void fillTeachersAdapterData(YxListAdapter1 YxListAdapter1, ArrayList<DMTeacher> teachers) {
		ArrayList<Integer> itemTypes = new ArrayList<Integer>();
		ArrayList<Object> data = new ArrayList<Object>();
		if (teachers == null) {
			// 测试。
			for (int i = 0; i < 3; i++) {
				itemTypes.add(YxDetailedInfoView1.TYPE_TEACHER_ITEM);
				data.add(new Object());
			}
		} else {
			// 将DMTeacher传给YxDetailedInfoView1
			for (DMTeacher teacher : teachers) {
				itemTypes.add(YxDetailedInfoView1.TYPE_TEACHER_ITEM);
				data.add(teacher);
			}
		}
		YxListAdapter1.setData(itemTypes, data);
	}
	
	private View.OnClickListener mClickListener = new View.OnClickListener() {
		
		@Override
		public void onClick(View arg0) {
			if (mCurrentCourse == null) {
				return;
			}
			
			switch (arg0.getId()) {
			case R.id.school_button:
				Intent intent = new Intent(getApplicationContext(), SchoolIntroductionActivity.class);
				intent.putExtra(NwUtils.KEY_ID, "" + mCurrentCourse.getSchoolId());
				startActivity(intent);
				break;
			case R.id.contact_now:
				// 部分课程不支持免费预约试听
				if (supportBook != 1) {
					UIHelper.showTips(arg0, "该课程不支持免费预约试听");
					break;
				}
				// 未登录
				if (UserLoginResponse.getInstance(getApplicationContext()) == null) {
					startActivityForResult(new Intent(getApplicationContext(),
							UserLoginActivity.class), REQ_CODE_LOGIN_FOR_REG);
				} else {
					bookCourse();
				}
				break;
			case R.id.dailer:
				Utils.dialPhoneNumber(CourseIntroductionActivity.this, mCurrentCourse);
				break;
//			case R.id.share:
//				
//				String param = "id=" + mCourseId;
//				UMSocialService controller = ShareUtils.initShareController(
//						CourseIntroductionActivity.this, NwUtils.SHARE_COURSE
//								+ param, mCurrentCourse);
//				controller.openShare(CourseIntroductionActivity.this, false);
//				
//				break;
			case R.id.favourite:
				if (mCurrentCourse == null) {
					return;
				}
				// 收藏
				// 未登录
				if (UserLoginResponse.getInstance(getApplicationContext()) == null) {
					startActivityForResult(new Intent(getApplicationContext(),
							UserLoginActivity.class), REQ_CODE_LOGIN_FOR_FAVOURITE);
				} else {
					favaouriteCourse();
				}
				break;
			case R.id.location_root:
				// 显示地图
				StatHelper.addKVEvent(mContext, "event_course_map_view",
						StatHelper.KEY_COURSE, mCourseId);
				Utils.showLocationInMap(CourseIntroductionActivity.this, mCurrentCourse.getSchoolGps(), 
						mCurrentCourse.getAddress(), mCurrentCourse.getCourseName());
				break;
			case R.id.wx_share:
			case R.id.pyq_share:
				dismissPopupWindowIfHave();
				break;
				
			case R.id.wb_share:
				dismissPopupWindowIfHave();
				mController.postShare(CourseIntroductionActivity.this,
						SHARE_MEDIA.SINA, mSnsPostListener);
				break;
			case R.id.qq_share:
				dismissPopupWindowIfHave();
				
				initQQ(CourseIntroductionActivity.this);
				setQQShare(CourseIntroductionActivity.this);
				
				mController.postShare(CourseIntroductionActivity.this,
						SHARE_MEDIA.QQ, mSnsPostListener);
				break;
				
			case R.id.qzone_share:
				dismissPopupWindowIfHave();
				initQzone(CourseIntroductionActivity.this);
				setQzoneShare(CourseIntroductionActivity.this);
				mController.postShare(CourseIntroductionActivity.this,
						SHARE_MEDIA.QZONE, null);
				break;
				
			default:
				mBaseClickListener.onClick(arg0);
				break;
			}
			
		}
	};
	private SnsPostListener mSnsPostListener = new SnsPostListener() {
		@Override
		public void onStart() {
			Toast.makeText(CourseIntroductionActivity.this,
					"开始分享.", Toast.LENGTH_SHORT).show();
		}

		@Override
		public void onComplete(SHARE_MEDIA platform,
				int eCode, SocializeEntity entity) {
			if (eCode == 200) {
				Toast.makeText(
						CourseIntroductionActivity.this,
						"分享成功.", Toast.LENGTH_SHORT).show();
			} else {
				String eMsg = "";
				if (eCode == -101) {
					eMsg = "没有授权";
				}
				Toast.makeText(
						CourseIntroductionActivity.this,
						"分享失败[" + eCode + "] " + eMsg,
						Toast.LENGTH_SHORT).show();
			}
		}
	};
	
	/// Share FUcntion - start
	private PopupWindow mPopupWindow;
	private Dialog mDialog;
	private UMSocialService mController;
//	private YxDetailedInfoView1 mCourseInfo;
//	private YxDetailedInfoView1 mAchievement;
//	private YxListAdapter1 mAchievementAdapter;
//	private YxListAdapter1 mCourseInfoAdapter;
//	private YxDetailedInfoView1 mTeachers;
//	private YxListAdapter1 mTearchersAdapter;
	private ScrollView mScrollView;
	private String mCourseId;
	public boolean mIsFavouriting = false;
	private View tabs;
	private CourseProductsView mProductView;

	// show social share dialog.
	protected void showShareDialog(View arg0) {
		tryShowDialog1(arg0);
	}
	
	private void tryShowDialog1(View view) {
		LinearLayout layout = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.segment_share_dialog,
                null);
		customizeShareDialog(layout);
        mPopupWindow = new PopupWindow(layout, LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT);
        mPopupWindow.setAnimationStyle(android.R.style.Animation_Dialog);
        mPopupWindow.showAtLocation(findViewById(R.id.root), Gravity.RIGHT | Gravity.BOTTOM, 0, 0);
        layout.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View arg0, MotionEvent arg1) {
				dismissPopupWindowIfHave();
				return false;
			}
		});
	}
	
	private void customizeShareDialog(LinearLayout layout) {
		String[] shareTitles = {
				"微信好友",
				"微信朋友圈",
				"新浪微博",
				"QQ好友",
				"QQ空间"
		};
		int[] iconIds = {
				R.drawable.t_wxhy,
				R.drawable.t_pyq,
				R.drawable.t_weibo,
				R.drawable.t_qq,
				R.drawable.t_qzone
		};
		int[] childIds = {
				R.id.wx_share,
				R.id.pyq_share,
				R.id.wb_share,
				R.id.qq_share,
				R.id.qzone_share
		};
		for (int i = 0; i < shareTitles.length; i++) {
			UIHelper.setDrawable(layout.findViewById(childIds[i]), R.id.icon, iconIds[i]);
			UIHelper.setText(layout.findViewById(childIds[i]), R.id.share, shareTitles[i]);
			UIHelper.setClickListener(layout, childIds[i], mClickListener);
		}
	}

	private void dismissPopupWindowIfHave() {
		if (mPopupWindow != null && mPopupWindow.isShowing()) {
			mPopupWindow.dismiss();
			mPopupWindow = null;
		}
	}
	
	private void tryShowDialog(View view) {
		// 获取期望window大小
		int[] sizes = Utils.getDisplayWidthHeight(this);
		int[] viewPosition = new int[2];
		int windowHeight = sizes[1] - viewPosition[1] - view.getHeight();
		
		if (mPopupWindow == null || !mPopupWindow.isShowing()) {
			initPopupWindow((int) (sizes[0] ),
					windowHeight, R.layout.segment_share_dialog, view);

			mDialog = new Dialog(this,
					android.R.style.Theme_Translucent_NoTitleBar);
			WindowManager.LayoutParams lp = mDialog.getWindow()
					.getAttributes();
			lp.dimAmount = 0.5f;
			mDialog.getWindow().setAttributes(lp);
			mDialog.getWindow().addFlags(
					WindowManager.LayoutParams.FLAG_DIM_BEHIND);
			mDialog.setCanceledOnTouchOutside(false);
			mPopupWindow.showAtLocation(findViewById(R.id.root), Gravity.BOTTOM
					| Gravity.LEFT, 0, 0);

		} 

		View root = mPopupWindow.getContentView();
	}
	
	
	
	private void initPopupWindow(int sugW, int sugH, int layoutId, View view) {
		View customView = LayoutInflater.from(view.getContext()).inflate(layoutId, null);
		mPopupWindow = new PopupWindow(customView, sugW, sugH);

		mPopupWindow.setTouchable(true);
		mPopupWindow.setOutsideTouchable(false);
		mPopupWindow.setBackgroundDrawable(getResources().getDrawable(
				android.R.color.transparent));

		Window window = getWindow();
		WindowManager.LayoutParams lp = window.getAttributes();
		lp.dimAmount = 1f;
		window.setAttributes(lp);
	}
	
	public void initShareController(Context context, String param) {
		mController = UMServiceFactory.getUMSocialService("com.umeng.share");
		// 设置分享内容
		// 设置分享图片, 参数2为图片的url地址
		mController.setShareContent(ShareTextHelper.getShareText(mCurrentCourse));
		UMImage image = new UMImage(this, R.drawable.logo);
		image.setTargetUrl("http://www.learnmore.com.cn/m/courseDetail.html?" + param);
		mController.setShareMedia(image);
		SHARE_MEDIA[] channels = new SHARE_MEDIA[] {
				SHARE_MEDIA.WEIXIN,
				SHARE_MEDIA.WEIXIN_CIRCLE,
				SHARE_MEDIA.QQ,
				SHARE_MEDIA.QZONE,
				SHARE_MEDIA.SINA
		};
		for (SHARE_MEDIA channel : channels) {
			mController.setAppWebSite(channel, "www.baidu.com");
		}
		// "http://www.manytu.com/m/courseDetail.html?" + param

		// web 图片
//		mController.setShareMedia(new UMImage(context, 
//                "http://www.baidu.com/img/bdlogo.png"));
		// 设置分享图片，参数2为本地图片的资源引用
		//mController.setShareMedia(new UMImage(getActivity(), R.drawable.icon));
		// 设置分享图片，参数2为本地图片的路径(绝对路径)
		//mController.setShareMedia(new UMImage(getActivity(), 
//		                                BitmapFactory.decodeFile("/mnt/sdcard/icon.png")));

		// 设置分享音乐
		//UMusic uMusic = new UMusic("http://sns.whalecloud.com/test_music.mp3");
		//uMusic.setAuthor("GuGu");
		//uMusic.setTitle("天籁之音");
		// 设置音乐缩略图
		
		//uMusic.setThumb("http://www.umeng.com/images/pic/banner_module_social.png");
		//mController.setShareMedia(uMusic);

		// 设置分享视频
		//UMVideo umVideo = new UMVideo(
//		          "http://v.youku.com/v_show/id_XNTE5ODAwMDM2.html?f=19001023");
		// 设置视频缩略图
		//umVideo.setThumb("http://www.umeng.com/images/pic/banner_module_social.png");
		//umVideo.setTitle("友盟社会化分享!");
		//mController.setShareMedia(umVideo);
	}
	
	private void initQQ(Activity activity) {
		//参数1为当前Activity， 参数2为开发者在QQ互联申请的APP ID，参数3为开发者在QQ互联申请的APP kEY.
		UMQQSsoHandler qqSsoHandler = new UMQQSsoHandler(activity, Constants.QQ_APP_ID,
		                Constants.QQ_APP_KEY);
		qqSsoHandler.addToSocialSDK(); 
	}
	
	private void initQzone(Activity activity) {
		//参数1为当前Activity， 参数2为开发者在QQ互联申请的APP ID，参数3为开发者在QQ互联申请的APP kEY.
		QZoneSsoHandler qZoneSsoHandler = new QZoneSsoHandler(activity, Constants.QQ_APP_ID,
		                Constants.QQ_APP_KEY);
		qZoneSsoHandler.addToSocialSDK();
	}
	
	private void initWX(Activity activity) {
		// wx967daebe835fbeac是你在微信开发平台注册应用的AppID, 这里需要替换成你注册的AppID
		String appID = Constants.WX_APP_ID;
		String appSecret = Constants.WX_APP_SECRET;
//		appID = "wx967daebe835fbeac";
//		appSecret = "5fa9e68ca3970e87a1f83e563c8dcbce";
		// 添加微信平台
		UMWXHandler wxHandler = new UMWXHandler(activity,appID,appSecret);
		wxHandler.addToSocialSDK();
		// 添加微信朋友圈
		UMWXHandler wxCircleHandler = new UMWXHandler(activity,appID,appSecret);
		wxCircleHandler.setToCircle(true);
		wxCircleHandler.addToSocialSDK();
	}
	
	private void setQQShare(Activity activity) {
		QQShareContent qqShareContent = new QQShareContent();
		//设置分享文字
		qqShareContent.setShareContent("来自友盟社会化组件（SDK）让移动应用快速整合社交分享功能 -- QQ");
		//设置分享title
		qqShareContent.setTitle("QQ, title");
		//设置分享图片
		qqShareContent.setShareImage(new UMImage(activity, R.drawable.logo));
		//设置点击分享内容的跳转链接
		qqShareContent.setTargetUrl("www.baidu.com");
		mController.setShareMedia(qqShareContent);
	}
	
	private void setQzoneShare(Activity activity) {
		QZoneShareContent qzone = new QZoneShareContent();
		//设置分享文字
		qzone.setShareContent("来自友盟社会化组件（SDK）让移动应用快速整合社交分享功能 -- QZone");
		//设置点击消息的跳转URL
		qzone.setTargetUrl("www.baidu.com");
		//设置分享内容的标题
		qzone.setTitle("QZone title");
		//设置分享图片
		qzone.setShareImage(new UMImage(activity, R.drawable.logo));
		mController.setShareMedia(qzone);
	}
	
	private void setQQShareType() {
		QQShareContent qqShareContent = new QQShareContent();
		qqShareContent.setShareContent("来自友盟社会化组件（SDK）让移动应用快速整合社交分享功能 -- QQ");
		qqShareContent.setTitle("hello, title");
		qqShareContent.setTargetUrl("你的URL链接");
		mController.setShareMedia(qqShareContent);
	}
	/// Share FUcntion - End

	private void favaouriteCourse() {
		if (mIsFavouriting) {
			return;
		}
		mIsFavouriting = true;
		FavouriteAsyncTask task = new FavouriteAsyncTask();
		task.execute(0);
	}

	private void bookCourse() {
		Intent intent;
		intent = new Intent(getApplicationContext(), ApointmentAuditionActivity.class);
		intent.putExtra(Yx.KEY_SHARE_OBJECT, mCurrentCourse);
		intent.putExtra(Yx.KEY_BOOK_TYPE, Yx.TYPE_ITEM_COURSE);
		intent.putExtra(Yx.KEY_BOOK_ITEM_ID, "" + mCourseId);
		intent.putExtra(Yx.KEY_BOOK_SCHOOL_NAME, mCurrentCourse.getSchoolFullName());
		intent.putExtra(Yx.KEY_BOOK_ITEM_NAME, mCurrentCourse.getCourseName());
		
		/// MTA stat start
		Properties prop = StatHelper.getBasicProp(CourseIntroductionActivity.this);
		prop.put(StatHelper.KEY_SCHOOL, mCurrentCourse.getSchool().getId());
		prop.put(StatHelper.KEY_COURSE, mCurrentCourse.getCourseId());
		StatService.trackCustomKVEvent(CourseIntroductionActivity.this, "event_course_reg", prop);
		/// MTA stat end
		
		startActivity(intent);
	}

	class FavouriteAsyncTask extends AsyncTask<Integer, Integer, ResponseObject> {

		@Override
		protected ResponseObject doInBackground(Integer... arg0) {
			UserLoginResponse ulRsp = UserLoginResponse.getInstance(getApplicationContext());
			if (ulRsp == null) {
				//TODO  需要登录。
				return new ResponseObject(-1, "");
			}
			
			JSONObject param = new JSONObject();
			try {
				param.put("id", "" + mCourseId);
				param.put("time", "" + System.currentTimeMillis());
			} catch (JSONException e) {
				e.printStackTrace();
			}
			
			try {
				ResponseObject ret = UserReg.requestFavouriteItem(ulRsp, Yx.TYPE_ITEM_COURSE, param, CourseIntroductionActivity.this);
				return ret;
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (JSONException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return new ResponseObject(-1, "");
		}
		
		@Override
		protected void onPostExecute(ResponseObject result) {
			super.onPostExecute(result);
			String text = "收藏";
			if (mCurrentCourse.getFavStatus() == 1) {
				text = "取消收藏";
			}
			mCurrentCourse.setFavStatus(mCurrentCourse.getFavStatus() == 1 ? 0 : 1);
			mActionBar.getCustomView().findViewById(R.id.favourite).setSelected(mCurrentCourse.getFavStatus() == 1);

			if (result.getCode() == MsgCode.SUCCESS) {
				Toast.makeText(getApplicationContext(), text + "成功", Toast.LENGTH_SHORT).show();
				
				Intent intent = new Intent();
				intent.putExtra(Yx.KEY_COURSE_OBJECT, mCurrentCourse);
				setResult(RESULT_OK, intent);
				
			} else if (result.getCode() == MsgCode.USER_SESSION_TIMEOUT_OR_NOTLOGIN){
				Toast.makeText(getApplicationContext(), MsgCode.descFor(result) , Toast.LENGTH_SHORT).show();
				startActivityForResult(new Intent(getApplicationContext(),
						UserLoginActivity.class), REQ_CODE_LOGIN_FOR_FAVOURITE);
			} else {
				Toast.makeText(getApplicationContext(), MsgCode.descFor(result), Toast.LENGTH_SHORT).show();
			}
			mIsFavouriting  = false;
		}
	}
	
	public String getCurCourseId() {
		return mCourseId;
	}

	public void setTeachersDataChangeNotifier(Observee dataChangeNotifier) {
		this.teachersDataChangeNotifier = dataChangeNotifier;
	}

	
	public void showProductsList(View view) {
		Intent intent = new Intent(this, ProductSelectionActivity.class);
		intent.putExtra(Yx.KEY_COURSE_OBJECT, mCurrentCourse);
		startActivity(intent);
	}
	
	private int getSupportBuyCount() {
		if (mCurrentCourse == null || mCurrentCourse.getProducts() == null) {
			return 0;
		} else {
			return mCurrentCourse.getProducts().size();
		}
	}
}
